﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FortuneHeavenCommon.ComMethod;
using System.Xml.Serialization;
using System.IO;
using FortuneHeavenBAL;
using FortuneHeavenCommon.DataMap;

namespace FortuneHeaven.Admin.Common
{
    public class AuthorityCenter
    {
        private static string configurl = "~/RoleConfig.xml";
        private static RoleAuth structure = null;

        public static RoleAuth Structure
        {
            get
            {
                if (structure == null)
                {
                    try
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(RoleAuth));

                        using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(configurl)))
                        {
                            return (RoleAuth)ser.Deserialize(reader);
                        }
                    }
                    catch (Exception exp)
                    {
                        structure = new RoleAuth();
                    }
                }
                return structure;
            }
        }

        public static bool ValidateUser(string user, string password, string validecode, ref string errorinfor)
        {
            if (WebSession.Session[ValidationCode.Name] == null)
            {
                errorinfor = "验证码失效";
                return false;
            }

            if (((string)WebSession.Session[ValidationCode.Name]).ToLower() != validecode.ToLower())
            {
                errorinfor = "验证码错误";
                return false;
            }

            AdminUserBO bo = new AdminUserBO();
            AdminUser ret = bo.CheckUserPwd(user, password);
            if (ret == null)
            {
                errorinfor = "帐号或者密码不正确";
                return false;
            }
            else
            {
                CurrentUserID = ret.ID;
                CurrentUserName = string.IsNullOrEmpty(ret.RealName) ? ret.LoginName : ret.RealName;
                IsAdmin = ret.IsAdmin == 1 ? true : false;
            }
            return true;
        }

        public static bool CheckAndChangePassword(string oldpassword, string password, string dbpwd, string validate, ref string error)
        {
            if (string.IsNullOrEmpty(oldpassword))
            {
                error = "老密码不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(password))
            {
                error = "新密码不能为空";
                return false;
            }
            if (dbpwd != password)
            {
                error = "两次输入密码不一致";
                return false;
            }
            if (string.IsNullOrEmpty(validate))
            {
                error = "验证码不能为空";
                return false;
            }
            if (WebSession.Session[ValidationCode.Name] == null)
            {
                error = "验证码失效";
                return false;
            }

            if (((string)WebSession.Session[ValidationCode.Name]).ToLower() != validate.ToLower())
            {
                error = "验证码错误";
                return false;
            }
            AdminUserBO bo = new AdminUserBO();
            AdminUser ret = bo.GetInfo(AuthorityCenter.CurrentUserID);
            if(ret !=null)
            {
                if (ret.Password.ToLower() != CommonEncrypt.Encrypt(oldpassword).ToLower())
                {
                    error = "老密码不正确";
                    return false;
                }
                else
                {
                    ret.Password = CommonEncrypt.Encrypt(password);
                    bo.Save(ret,false);
                    return true;
                }
            }
            error = "用户已不在登陆状态";
            return false;
        }

        public static bool IsAuth(string auth, string funcNO)
        {
            if (string.IsNullOrEmpty(auth))
            {
                string[] content = auth.Split(',');
                foreach (string no in content)
                {
                    if (no == funcNO.Trim().ToLower())
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public static bool CheckLogin()
        {
            if (CurrentUserID < 0)
            {
                HttpContext.Current.Response.Clear();
                string script = string.Format("<script>if(parent) {{parent.location='{0}';}}else {{document.location='{0}';}} </script>",
                    VirtualPathUtility.ToAbsolute("~/Login.aspx"));
                HttpContext.Current.Response.Write(script);
                HttpContext.Current.Response.End();
                return false;
            }
            return true;
        }

        public static bool CheckPermission(string pageID)
        {
            if (IsAdmin)
            {
                return true;
            }
            AdminUserBO bo = new AdminUserBO();
            AdminUser user = bo.GetUser(CurrentUserID);
            
            if (user != null && user.RoleList != null)
            {
                foreach (Role ro in user.RoleList)
                {
                    if (CheckRolePermission(pageID, ro))
                    {
                        return true;
                    }
                }
            }
            HttpContext.Current.Response.Clear();
            string script = string.Format("<script>alert('没有权限查看该页面！'); if(parent) {parent.location='{0}'};else {document.location='{0}';} </script>",
                VirtualPathUtility.ToAbsolute("~/Error.htm"));
            HttpContext.Current.Response.Write(script);
            HttpContext.Current.Response.End();
            return false;
        }

        private static bool CheckRolePermission(string pageID, Role role)
        {
            if (!string.IsNullOrEmpty(role.Auth))
            {
                string[] content = role.Auth.Split(',');
                foreach (string k in content)
                {
                    if (k == pageID)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static RoleAuth GetCurrentAuth()
        {
            if (IsAdmin)
            {
                RoleAuth ret = (RoleAuth)Structure.Clone();
                foreach (Module mo in ret.Modules)
                {
                    mo.IsAuth = true;
                    foreach (Function fu in mo.Functions)
                    {
                        fu.IsAuth = true;
                    }
                }
                return ret;
            }
            AdminUserBO bo = new AdminUserBO();
            AdminUser user = bo.GetUser(CurrentUserID);
            if (user != null && user.RoleList != null)
            {
                RoleAuth ret = (RoleAuth)Structure.Clone();
                foreach (Role r in user.RoleList)
                {
                    SetRoleAuthFromRoleList(ret, r);
                }
                return ret;
            }
            return null;
        }

        private static void SetRoleAuthFromRoleList(RoleAuth auth, Role role)
        {
            List<string> funcs = GetAuthFunc(role.Auth);
            foreach (Module mo in auth.Modules)
            {
                foreach (Function fu in mo.Functions)
                {
                    if (FindFunc(funcs, fu.FunctionNO))
                    {
                        fu.IsAuth = true;
                        mo.IsAuth = true;
                    }
                }
            }
        }

        public static RoleAuth GetAuth(int id)
        {
            RoleAuth ret = (RoleAuth)Structure.Clone();
            if (id < 0)
            {
                return ret;
            }
            RoleBO bo = new RoleBO();
            Role role = bo.GetInfo(id);
            List<string> funcs = GetAuthFunc(role.Auth);
            if (role != null)
            {
                foreach (Module mo in ret.Modules)
                {
                    mo.IsAuth = false;
                    foreach (Function fu in mo.Functions)
                    {
                        if (FindFunc(funcs, fu.FunctionNO))
                        {
                            fu.IsAuth = true;
                            mo.IsAuth = true;
                        }
                        else
                        {
                            fu.IsAuth = false;
                        }
                    }
                }
            }
            return ret;
        }

   
        private static bool FindFunc(List<string> content, string funcno)
        {
            if (content != null)
            {
                foreach (string fun in content)
                {
                    if (fun == funcno)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static List<string> GetAuthFunc(string auth)
        {
            List<string> content = new List<string>();
            if (!string.IsNullOrEmpty(auth))
            { 
               string[] ret = auth.Split(',');
               foreach(string k in ret)
               {
                content.Add( k.Trim());
               }
            }
            return content;
        }

        public static string SetAuthFunc(List<string> funcs)
        {
            string ret="";
            foreach (string cont in funcs)
            {
                ret = ret + cont + ",";
            }
            if (ret.EndsWith(","))
            {
                ret = ret.TrimEnd(',');
            }
            return ret;
        }


        public static void ClearSession()
        {
            WebSession.Session.Remove("UserID");
            WebSession.Session.Remove("UserName");
            WebSession.Session.Remove("IsAdmin");
        }

        public static int CurrentUserID
        {
            get {
                object oj =WebSession.Session["UserID"];
                if (oj == null)
                {
                    return -1;
                }
               
                return (int)(oj);
            }
            set
            {
                WebSession.Session["UserID"] = value;
            }
        }

        public static string CurrentUserName
        {
            get
            {
                object oj = WebSession.Session["UserName"];
                if (oj == null)
                {
                    return "";
                }

                return (string)(oj);
            }
            set
            {
                WebSession.Session["UserName"] = value;
            }
        }

        public static bool IsAdmin
        {
            get
            {
                object obj  =WebSession.Session["IsAdmin"];
                if (obj == null)
                {
                    return false;
                }
                return (bool)obj;
            }
            set
            {
                WebSession.Session["IsAdmin"] = value;
            }
        }

    }
}